<?php

namespace app\logic\single\pay;

use EasyWeChat\Factory;

class WxPaySingle
{
    private static $inc;
    private $notify='https://api.jcdjpool.com/api/notify/wx';
    /**
     * @var \EasyWeChat\Payment\Application
     */
    private $app;


    private function __clone(){

    }
    private function __construct()
    {
        $this->app = Factory::payment(config('wechat'));
    }

    public static function getInstance(): WxPaySingle
    {
        if(is_null(self::$inc)){
            self::$inc = new self();
        }
        return self::$inc;
    }
    function pay($order=[],$terminal='h5',$type='music',$title='购买音乐'){
        switch ($terminal){
            case 'wx':
                $trade_type='JSAPI';
                $order['order_no'].='_'.rand(1,9999);
                break;
            case 'h5':
                $trade_type='MWEB';
                $order['order_no'].='_'.rand(1,9999);
                break;
            case 'pc':
            default:
                $trade_type='NATIVE';
                $order['order_no'].='_'.rand(1,9999);
                break;
        }
        $pay=[
            'body' => $title,
            'out_trade_no' => $order['order_no'],
            'attach'=>$type,
            'total_fee' => $order['pay_price'] * 100,
            'notify_url' => $this->notify, // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => $trade_type,
        ];
        if($trade_type == 'JSAPI'){
            $pay['openid']=$order['openid'];
        }
        $result =$this->app->order->unify($pay);
        if (
            isset($result['result_code']) && $result['result_code'] == 'SUCCESS' &&
            isset($result['return_code']) && $result['return_code'] == 'SUCCESS')
        {
            $prepayId = $result['prepay_id'];
            return $this->app->jssdk->sdkConfig($prepayId);
        } else {
            return $result;
        }
    }


    public function refund($order,$type)
    {

        return  $this->app->refund->byTransactionId(
            $order['trade_no'],
            $order['refund_order_no'],
            $order['pay_price'] * 100,
            $order['pay_price'] * 100, [
            'refund_desc' => '订单退款',
            'notify_url' => "https://api.jcdjpool.com/api/notify/wx/{$type}_refund"//退款回调地址
        ]);
    }
    function getApp(){
        return $this->app;
    }
}